package org.jproxy;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JProxyServlet extends HttpServlet
{
	private static final long serialVersionUID = -5559337915486000390L;

	private RequestProcessor processor;

	@Override
	public void init(ServletConfig config) throws ServletException
	{
		System.setProperty("jproxy.classloader.path", config.getServletContext().getRealPath("/WEB-INF/"));
		processor = new RequestProcessor();
	}

	//---------------->request<----------------
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		ResourcePool pool = ResourcePool.getInstance();
		pool.putHttpServletRequest(request);
		try
		{
			process(request, response);
		}finally
		{
			pool.removeHttpServletRequest();
		}

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		ResourcePool pool = ResourcePool.getInstance();
		pool.putHttpServletRequest(request);
		try
		{
			process(request, response);
		}finally
		{
			pool.removeHttpServletRequest();
		}
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
	{
		long begin = System.currentTimeMillis();
		String clazz = request.getPathInfo().substring(1);
		String json = request.getParameter("json");
		String result = processor.process(clazz, json);
		System.out.println(">>>> time" + (System.currentTimeMillis() - begin));
		System.out.println("result-> " + result);
		try
		{
			response.getWriter().append(result);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
